package weeek11.topic08;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;

import java.util.Collections;

/**
 * redis lock
 * @author lfy
 */
public class RedisLock {
    public static void main(String[] args) {
        String key1 = "k1";
        String r1 = "r1";
        String key2 = "k2";
        String r2 = "r2";
        RedisLock redisLock = new RedisLock("127.0.0.1",6379);

        boolean l1 = redisLock.lock(key1, r1, 3);
        System.out.println("锁住了key1:"+l1);
        boolean l2 = redisLock.lock(key2, r2, 3);
        System.out.println("锁住了key2:"+l2);
        boolean l3 = redisLock.lock(key1, r1, 3);
        System.out.println("尝试再次锁住key1:"+l3);

        redisLock.release(key1,r1);
        boolean lock = redisLock.lock(key1, r1, 3);
        System.out.println("释放锁后，尝试再次锁住key1:"+lock);
    }
    private final JedisPool jedisPool;

    public RedisLock(String host, int port) {
        jedisPool = new JedisPool(host, port);
    }

    /**
     * 加锁
     *
     * @param lockKey
     * @param random
     * @param seconds
     * @return
     */
    public boolean lock(String lockKey, String random, long seconds) {
        try (Jedis jedis = jedisPool.getResource()) {
            SetParams params = new SetParams().ex(seconds).nx();
            return "OK".equals(jedis.set(lockKey, random,params));
        }
    }

    /**
     * 释放锁
     *
     * @param lockKey
     * @param random
     * @return
     */
    public boolean release(String lockKey, String random) {
        String luaScript = "if redis.call('get',KEYS[1]) == ARGV[1] then " + "return redis.call('del',KEYS[1]) else return 0 end";
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.eval(luaScript, Collections.singletonList(lockKey), Collections.singletonList(random)).equals(1L);
        }
    }
}